package com.ycsj.goldmedalnewconcept.fragment;

import java.io.File;
import java.util.List;
import java.util.TreeMap;

import android.R.integer;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvaluator;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.activity.AnswerListDetailsActivity;
import com.ycsj.goldmedalnewconcept.adapter.LazyBaseFragment;
import com.ycsj.goldmedalnewconcept.bean.AnswerInfo;
import com.ycsj.goldmedalnewconcept.bean.TopicInfo.QuestionListBean;
import com.ycsj.goldmedalnewconcept.bean.TopicInfo.QuestionListBean.DetailListBean;
import com.ycsj.goldmedalnewconcept.iflytek.ise.AVLoadingIndicatorView;
import com.ycsj.goldmedalnewconcept.iflytek.ise.Result;
import com.ycsj.goldmedalnewconcept.iflytek.ise.XmlResultParser;
import com.ycsj.goldmedalnewconcept.pickerview.utils.PickerViewAnimateUtil;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;

/**
 * 答题进度的Fragent
 * 
 * @author Administrator
 *
 */
public class AnswerFragment extends LazyBaseFragment implements
		View.OnClickListener, OnTouchListener {

	// 顶部的线性布局
	private LinearLayout llTopPlay;

	// 顶部的喇叭和播放图片
	private ImageView lvTopLaBa;

	// 展示题目的TextView
	private TextView tvTopic;

	// 答案A,B,C相关控件
	private LinearLayout llA, llB, llC;
	private ImageView lvA, lvB, lvC;
	private TextView tvA, tvB, tvC;
	private ImageView lvAstate, lvBstate, lvCstate;

	// 底部的整体布局
	private LinearLayout llBottom;

	// 底部的播放音频的按钮
	private ImageView lvReplay;

	// 底部的录音按钮
	private ImageView lvRecord;

	// 底部的记录显示分数的TextView
	private TextView tvScore;

	// 加载框的线性布局
	private LinearLayout llLoading;

	// 加载框对象
	private AVLoadingIndicatorView avind;

	// 下一题按钮
	private Button btNext;

	// 讯飞SDK对象
	private SpeechEvaluator mSpeechEvaluator;

	// 页面的题目信息对象
	private QuestionListBean info;

	// 用于记录正确答案的字符串
	private String answerQuestion;

	// 用于记录内容的语音地址的字符串
	private String audio;

	// 用于记录用户选择答案的字符串
	private String answerChoose;

	// 用于记录题目答案选项的集合
	private List<DetailListBean> infos;

	// MediaPlayer对象
	private MediaPlayer player;

	// 帧动画对象
	private AnimationDrawable animationDrawable;

	private AnimationDrawable popAnimationDrawable;

	// 发送翻页广播的Action
	public static final String NEXT_ACTION = "nextaction";

	// 当前页面数和总的页面数量
	private int postion, totalSize;

	// 当前的页面的LessionId
	private String lessionId;

	// 用于控制第一次点击播放状态,默认是没有录音文件的
	private boolean hasRecord = false;

	/**
	 * 录音的弹框PopUpWinow相关
	 */
	private View view;
	private ImageView lvPopRecord;
	private PopupWindow popupWindow;

	// 控制松手是否显示加载框的标记
	private boolean isShowDialog = true;

	/**
	 * 对外提供的生成该类对象的方法,不可单例
	 * 
	 * @return
	 */
	public static AnswerFragment newInstance(QuestionListBean info, int pos,
			int totalSzie, String lessionId) {

		AnswerFragment answerFragment = new AnswerFragment();
		// 通过arguments携带页面数据
		Bundle bundle = new Bundle();
		bundle.putSerializable("data", info);
		bundle.putInt("position", pos);
		bundle.putInt("totalSize", totalSzie);
		bundle.putString("lessionId", lessionId);
		answerFragment.setArguments(bundle);
		return answerFragment;
	}

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_answer;
	}

	@Override
	public void lazyInit(View view, Bundle savedInstanceState) {

	}

	/**
	 * 注册页面切换停止播放的按钮
	 */
	private void initRegisterBroadCast() {
		IntentFilter filter = new IntentFilter(
				"com.ycsj.goldmedalnewconcept.stopplay");
		getActivity().registerReceiver(new MyReceiver(), filter);
	}

	@Override
	protected void init(View view, Bundle savedInstanceState) {
		super.init(view, savedInstanceState);

		// 获取页面数据
		getData();

		// 初始化控件
		initView(view);

		// 设置初始状态
		initState();

		// 设置页面数据
		setData();

		// 配置讯飞SDK对象的参数
		setParams();

		// 设置监听的方法
		InitListener();

		// 注册广播
		initRegisterBroadCast();
	}

	/**
	 * 初始化View的方法
	 */
	private void initView(View view) {
		llTopPlay = (LinearLayout) view.findViewById(R.id.ll_top_play);
		llA = (LinearLayout) view.findViewById(R.id.ll_a);
		llB = (LinearLayout) view.findViewById(R.id.ll_b);
		llC = (LinearLayout) view.findViewById(R.id.ll_c);
		lvTopLaBa = (ImageView) view.findViewById(R.id.lv_top_laba);
		tvTopic = (TextView) view.findViewById(R.id.tv_topic);
		lvA = (ImageView) view.findViewById(R.id.lv_a);
		lvB = (ImageView) view.findViewById(R.id.lv_b);
		lvC = (ImageView) view.findViewById(R.id.lv_c);
		tvA = (TextView) view.findViewById(R.id.tv_a);
		tvB = (TextView) view.findViewById(R.id.tv_b);
		tvC = (TextView) view.findViewById(R.id.tv_c);
		lvAstate = (ImageView) view.findViewById(R.id.lv_a_state);
		lvBstate = (ImageView) view.findViewById(R.id.lv_b_state);
		lvCstate = (ImageView) view.findViewById(R.id.lv_c_state);
		lvReplay = (ImageView) view.findViewById(R.id.lv_replay);
		lvRecord = (ImageView) view.findViewById(R.id.lv_record);
		tvScore = (TextView) view.findViewById(R.id.tv_score);
		btNext = (Button) view.findViewById(R.id.bt_next);
		llLoading = (LinearLayout) view.findViewById(R.id.ll_loading);
		avind = (AVLoadingIndicatorView) view.findViewById(R.id.avind);
		llBottom = (LinearLayout) view.findViewById(R.id.ll_botttom);
	}

	/**
	 * 初始进入设置状态的方法
	 */
	private void initState() {
		// 初次进入让顶部的喇叭布局不进行显示
		llTopPlay.setVisibility(View.GONE);

		// 初次进入A,B,C答案的状态不进行显示
		lvAstate.setVisibility(View.INVISIBLE);
		lvBstate.setVisibility(View.INVISIBLE);
		lvCstate.setVisibility(View.INVISIBLE);

		// 底部的下一题,播放,录音,记录分数都进行隐藏
		llBottom.setVisibility(View.INVISIBLE);
		lvReplay.setVisibility(View.INVISIBLE);
		lvRecord.setVisibility(View.INVISIBLE);
		tvScore.setVisibility(View.INVISIBLE);
		btNext.setVisibility(View.INVISIBLE);
		// 设置底部按钮的文字
		if (postion != totalSize - 1) {
			// 表示不是最后一个
			btNext.setText("下一页");
		} else {
			// 是最后一个
			btNext.setText("下一页");
		}
	}

	/**
	 * 设置监听的方法
	 */
	@SuppressWarnings("deprecation")
	private void InitListener() {
		llTopPlay.setOnClickListener(this);
		llA.setOnClickListener(this);
		llB.setOnClickListener(this);
		llC.setOnClickListener(this);
		lvReplay.setOnClickListener(this);
		btNext.setOnClickListener(this);
		// 设置触摸事件
		lvRecord.setOnTouchListener(this);
	}

	/**
	 * 获取当前答页面的题目对象
	 */
	private void getData() {
		info = (QuestionListBean) getArguments().getSerializable("data");
		postion = getArguments().getInt("position");
		totalSize = getArguments().getInt("totalSize");
		lessionId = getArguments().getString("lessionId");
	}

	/**
	 * 设置页面数据的方法
	 */
	private void setData() {
		if (info == null) {
			return;
		} else {
			// 记录当前题目的正确答案
			answerQuestion = info.getQuestion_answer();

			// 记录当前题目播放的音频地址
			audio = info.getAudio();

			// 设置题目信息
			// 获取题目内容
			String questionContent = info.getQuestion_content();
			// 将其中的"填空"用下划线取代
			String newContent = questionContent.replaceAll("填空", "_______");
			tvTopic.setText(newContent);

			infos = info.getDetail_list();
			tvA.setText(infos.get(0).getDetail_content());
			tvB.setText(infos.get(1).getDetail_content());
			tvC.setText(infos.get(2).getDetail_content());
		}
	}

	/**
	 * 点击事件
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_top_play:
			// 顶部的点击播放
			doPlayContent();
			break;

		case R.id.ll_a:
			// 答案A的外层布局
			doClickAaction();
			break;

		case R.id.ll_b:
			// 答案B的外层布局
			doClickBaction();
			break;

		case R.id.ll_c:
			// 答案C的外层布局
			doClickCaction();
			break;

		case R.id.lv_replay:
			// 播放
			doPlayAction();
			break;

		case R.id.lv_record:
			// 录音
			doRecordAction();
			break;

		case R.id.bt_next:
			// 下一题按钮的点击事件
			doNextAction();
			break;

		default:
			break;
		}
	}

	/**
	 * 点击下一题的点击事件
	 */
	private void doNextAction() {
		if (postion != totalSize - 1) {
			// 不是最后一页,就发送广播
			// 发送一个广播通知FollowReadDetailsActivity去进行ViewPager的翻页处理
			Intent intent = new Intent(NEXT_ACTION);
			getActivity().sendBroadcast(intent);
		} else {
			// 跳转到详情页面

			Intent intent = new Intent(getActivity(),
					AnswerListDetailsActivity.class);
			intent.putExtra("lESSON_ID", lessionId);
			startActivity(intent);
		}

	}

	/**
	 * 点击顶部小喇叭部分按钮的方法
	 */
	private void doPlayContent() {
		try {
			// 如果没有音频地址,直接返回
			if (TextUtils.isEmpty(audio)) {
				return;
			}

			// 给顶部的图片设置帧动画
			lvTopLaBa.setImageResource(R.drawable.lv_frame_b);

			// 获取帧动画对象
			animationDrawable = (AnimationDrawable) lvTopLaBa.getDrawable();

			// 播放内容音乐
			if (null == player) {
				// 没有播放对象
				// 如果播放器为null,就创建一个播放器
				player = new MediaPlayer();
				player.setDataSource(audio);
			} else {
				// 有播放对象
				player.release();
				player = null;
				player = new MediaPlayer();
				player.setDataSource(audio);
			}

			// 恢复底部的播放按钮的状态
			lvReplay.setImageResource(R.drawable.playcloze);

			// 设置准备监听
			player.setOnPreparedListener(new OnPreparedListener() {

				@Override
				public void onPrepared(MediaPlayer mp) {
					// 开始播放
					player.start();

					// 执行帧动画
					if (null != animationDrawable) {
						animationDrawable.start();
					}
				}
			});

			// 同步完成
			player.prepareAsync();

			// 设置播放监听
			player.setOnCompletionListener(new topLabaListener());

		} catch (Exception e) {
			Log.i("test", e.toString());
		}
	}

	/**
	 * 点击答案A的操作
	 */
	private void doClickAaction() {
		if (answerQuestion.equals(answerChoose)) {
			// 如果题目的正确答案已经匹配了用户选择的答案,则再次点击的时候无效
			return;
		} else {
			if (lvAstate.getVisibility() == View.VISIBLE) {
				return;
			}
			// 记录下用户选择的答案
			answerChoose = infos.get(0).getDetail_content();
			// 与正确答案做对比
			lvAstate.setVisibility(View.VISIBLE);
			lvA.setImageResource(R.drawable.answer_a_select);
			if (answerQuestion.equals(answerChoose)) {
				// 用户选择的答案是正确答案,显示答案A的状态
				lvAstate.setImageResource(R.drawable.rightcloze);

				// lvB.setImageResource(R.drawable.answer_b_select_normal);
				lvBstate.setVisibility(View.VISIBLE);
				lvBstate.setImageResource(R.drawable.errorcloze);

				// lvC.setImageResource(R.drawable.answer_c_select_normal);
				lvCstate.setVisibility(View.VISIBLE);
				lvCstate.setImageResource(R.drawable.errorcloze);

				// 让顶部的录音喇叭显示
				llTopPlay.setVisibility(View.VISIBLE);

				// 改变背景
				llA.setBackgroundResource(R.drawable.ll_answer_bg);

				// 改变文字颜色
				tvA.setTextColor(getResources().getColor(
						R.color.answer_tv_select));

				llB.setBackgroundResource(R.drawable.ll_answer_normal_bg);
				tvB.setTextColor(getResources().getColor(
						R.color.answer_tv_normal));

				llC.setBackgroundResource(R.drawable.ll_answer_normal_bg);
				tvC.setTextColor(getResources().getColor(
						R.color.answer_tv_normal));

				// 回显答案
				// 获取题目内容
				String newContent = info.getDialogue();

				setRedAnswer(newContent, infos.get(0).getDetail_content());

				// 播放选择正确答案后的录音
				playRightAnswer(R.raw.rightmp3);

				// 底部的状态进行显示
				setBottomState();

			} else {
				// 用户选择的答案不是正确答案
				lvAstate.setImageResource(R.drawable.errorcloze);

				// 改变A的状态
				lvA.setImageResource(R.drawable.answer_a_select_normal);

				// 播放选择错误答案后的录音
				playRightAnswer(R.raw.errormp3);
			}
		}
	}

	/**
	 * 点击答案B的操作
	 */
	private void doClickBaction() {
		if (answerQuestion.equals(answerChoose)) {
			// 如果题目的正确答案已经匹配了用户选择的答案,则再次点击的时候无效
			return;
		} else {
			if (lvBstate.getVisibility() == View.VISIBLE) {
				return;
			}
			// 记录下用户选择的答案
			answerChoose = infos.get(1).getDetail_content();
			// 与正确答案做对比
			lvBstate.setVisibility(View.VISIBLE);
			lvB.setImageResource(R.drawable.answer_b_select);
			if (answerQuestion.equals(answerChoose)) {
				// 用户选择的答案是正确答案,显示答案A的状态
				lvBstate.setImageResource(R.drawable.rightcloze);

				// lvA.setImageResource(R.drawable.answer_a_select_normal);
				lvAstate.setVisibility(View.VISIBLE);
				lvAstate.setImageResource(R.drawable.errorcloze);

				// lvC.setImageResource(R.drawable.answer_c_select_normal);
				lvCstate.setVisibility(View.VISIBLE);
				lvCstate.setImageResource(R.drawable.errorcloze);

				// 让顶部的录音喇叭显示
				llTopPlay.setVisibility(View.VISIBLE);

				// 改变背景
				llA.setBackgroundResource(R.drawable.ll_answer_normal_bg);
				// 改变文字颜色
				tvA.setTextColor(getResources().getColor(
						R.color.answer_tv_normal));

				llB.setBackgroundResource(R.drawable.ll_answer_bg);
				tvB.setTextColor(getResources().getColor(
						R.color.answer_tv_select));

				llC.setBackgroundResource(R.drawable.ll_answer_normal_bg);
				tvC.setTextColor(getResources().getColor(
						R.color.answer_tv_normal));

				// 回显答案
				// 获取题目内容
				String newContent = info.getDialogue();

				setRedAnswer(newContent, infos.get(1).getDetail_content());

				// 播放选择正确答案后的录音
				playRightAnswer(R.raw.rightmp3);

				// 底部的状态进行显示
				setBottomState();

			} else {
				// 用户选择的答案不是正确答案
				lvBstate.setImageResource(R.drawable.errorcloze);
				// 改变B的状态
				lvB.setImageResource(R.drawable.answer_b_select_normal);
				// 播放选择错误答案后的录音
				playRightAnswer(R.raw.errormp3);
			}
		}
	}

	/**
	 * 回显答案并且进行红色显示的方法
	 * 
	 * @param newContent
	 * @param answer
	 */
	private void setRedAnswer(String newContent, String answer) {

		// 对答案进行;切割
		String[] answers = answer.split(";");
		SpannableStringBuilder spannable = new SpannableStringBuilder(
				newContent);

		// 获取切割的字符串在题目中的位置
		for (int i = 0; i < answers.length; i++) {

			int startIndex = newContent.indexOf(answers[i]);

			int endIndex = startIndex + answers[i].length();

			try {
				spannable.setSpan(new ForegroundColorSpan(Color.RED), startIndex,
						endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("error", e.toString());
			}
		}
		tvTopic.setText(spannable);
	}

	/**
	 * 点击答案C的操作
	 */
	private void doClickCaction() {

		if (answerQuestion.equals(answerChoose)) {
			// 如果题目的正确答案已经匹配了用户选择的答案,则再次点击的时候无效
			return;
		} else {
			// 表示用户已经选择过答案C了
			if (lvCstate.getVisibility() == View.VISIBLE) {
				return;
			}
			// 记录下用户选择的答案
			answerChoose = infos.get(2).getDetail_content();
			// 与正确答案做对比
			lvCstate.setVisibility(View.VISIBLE);
			lvC.setImageResource(R.drawable.answer_c_select);
			if (answerQuestion.equals(answerChoose)) {
				// 用户选择的答案是正确答案,显示答案A的状态
				lvCstate.setImageResource(R.drawable.rightcloze);

				// lvA.setImageResource(R.drawable.answer_a_select_normal);
				lvAstate.setVisibility(View.VISIBLE);
				lvAstate.setImageResource(R.drawable.errorcloze);

				// lvB.setImageResource(R.drawable.answer_b_select_normal);
				lvBstate.setVisibility(View.VISIBLE);
				lvBstate.setImageResource(R.drawable.errorcloze);

				// 让顶部的录音喇叭显示
				llTopPlay.setVisibility(View.VISIBLE);

				// 改变背景
				llA.setBackgroundResource(R.drawable.ll_answer_normal_bg);
				// 改变文字颜色
				tvA.setTextColor(getResources().getColor(
						R.color.answer_tv_normal));

				llB.setBackgroundResource(R.drawable.ll_answer_normal_bg);
				tvB.setTextColor(getResources().getColor(
						R.color.answer_tv_normal));

				llC.setBackgroundResource(R.drawable.ll_answer_bg);
				tvC.setTextColor(getResources().getColor(
						R.color.answer_tv_select));

				// 回显答案
				// 获取题目内容
				String newContent = info.getDialogue();

				// 将其中的"填空"用下划线取代
				setRedAnswer(newContent, infos.get(2).getDetail_content());

				// 播放选择正确答案后的录音
				playRightAnswer(R.raw.rightmp3);

				// 底部的状态进行显示
				setBottomState();
			} else {
				// 用户选择的答案不是正确答案
				lvCstate.setImageResource(R.drawable.errorcloze);
				// 改变C的状态
				lvC.setImageResource(R.drawable.answer_c_select_normal);
				// 播放选择错误答案后的录音
				playRightAnswer(R.raw.errormp3);
			}
		}
	}

	/**
	 * 同步设置底部的播放,录音显示的方法
	 */
	private void setBottomState() {
		llBottom.setVisibility(View.VISIBLE);
		lvReplay.setVisibility(View.VISIBLE);
		lvRecord.setVisibility(View.VISIBLE);
	}

	/**
	 * 底部播放本地录音文件的方法
	 */
	private void doPlayAction() {
		// 获取录音文件的地址
		if (hasRecord) {

			// 停止动画
			if (null != animationDrawable) {
				animationDrawable.stop();
			}
			// 恢复顶部喇叭的图标
			lvTopLaBa.setImageResource(R.drawable.lb);

			// 创建音频播放对象
			if (player != null) {
				player.release();
				player = null;
				player = new MediaPlayer();
			} else {
				player = new MediaPlayer();
			}
			// 设置完成播放的监听
			player.setOnCompletionListener(new lvReplayListener());

			// 播放录制的本地音频
			try {
				if (TextUtils.isEmpty(info.getAudio())) {
					UiHelper.toast(getActivity(), "请先录音");
					return;
				}
				
				player.setDataSource(info.getAudio());

				player.prepareAsync();

				player.setOnPreparedListener(new OnPreparedListener() {
					@Override
					public void onPrepared(MediaPlayer mp) {
						player.start();
						// 改变图标
						lvReplay.setImageResource(R.drawable.stopcloze);
					}
				});

			} catch (Exception e) {
				Log.i("test", e.toString());
			}
		} else {
			// 无存放的音频文件
			UiHelper.toast(getActivity(), "请先录音");
			return;
		}
	}

	/**
	 * 语音评测的方法
	 */
	private void doRecordAction() {

		// 清空播放器的播放状态
		// 释放资源对象
		if (player != null) {
			player.release();
		}

		// 设置顶部喇叭的图片
		lvTopLaBa.setImageResource(R.drawable.lb);

		// 恢复底部的播放按钮的状态
		lvReplay.setImageResource(R.drawable.playcloze);

		// 停止动画
		if (null != animationDrawable) {
			animationDrawable.stop();
		}

		// 震动手机
		Vibrator vibrator = (Vibrator) getActivity().getSystemService(
				Service.VIBRATOR_SERVICE);
		vibrator.vibrate(500);

		if (mSpeechEvaluator == null) {
			return;
		}

		// 重新配置讯飞的录音存放位置
		mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
				Environment.getExternalStorageDirectory().getAbsolutePath()
						+ "/msc/" + "ice" + postion + ".wav");

		// 开启评测功能
		mSpeechEvaluator.startEvaluating(info.getSpeechtest(), null,
				new EvaluatorListener() {

					// volume音量值0~30，data音频数据
					@Override
					public void onVolumeChanged(int volume, byte[] data) {

					}

					// 结果回调，评测过程中可能会多次调用该方法，isLast为true则为最后结果
					@SuppressWarnings({ "static-access", "static-access" })
					@Override
					public void onResult(EvaluatorResult result, boolean isLast) {
						if (isLast) {
							StringBuilder builder = new StringBuilder();
							builder.append(result.getResultString());

							XmlResultParser resultParser = new XmlResultParser();
							Result result1 = resultParser.parse(result
									.getResultString());

							// 处理乱读的问题
							if (!TextUtils.isEmpty(builder)) {
								float a = result1.total_score;
								float b = (float) (Math.round(a * 10)) / 10;
								isShowDialog = false;

								// 更改录音文件状态证明已经录音
								hasRecord = true;

								if (null != popupWindow
										&& popupWindow.isShowing()) {
									popupWindow.dismiss();
								}

								llLoading.setVisibility(View.INVISIBLE);
								tvScore.setVisibility(View.VISIBLE);
								tvScore.setText(b + " 分");

								// 更新集合中保存的对应位置的AnswerInfo
								String answerJson = SPUtils.getString(
										getActivity(), lessionId);

								// 跟新对应位置的Bean信息
								List<AnswerInfo> answerDatas = GsonUtil
										.jsonToList(answerJson,
												AnswerInfo[].class);

								AnswerInfo answerInfo = answerDatas
										.get(postion);
								answerInfo.score = b;
								answerInfo.audioPath = getAmrPath(postion);

								// 更新Info的播放文件
								info.setAudio(getAmrPath(postion));

								// 更新Sp中保存的值
								SPUtils.put(getActivity(), lessionId,
										GsonUtil.listToJson(answerDatas));

								// 显示评分按钮后将下一步按钮显示出来
								btNext.setVisibility(View.VISIBLE);

								// 播放科大讯飞的评分语音
								AssetManager assetManager = getActivity()
										.getAssets();
								if (player != null) {
									player.release();
									player = null;
									player = new MediaPlayer();
								} else {
									player = new MediaPlayer();
								}
								// 设置完成监听,主要作用是为了播放完成后让顶部的喇叭和底部左边的播放按钮变成可点击状态
								player.setOnCompletionListener(new setEnableListener());

								try {
									AssetFileDescriptor fileDescriptor1 = assetManager
											.openFd("1.mp3");
									AssetFileDescriptor fileDescriptor2 = assetManager
											.openFd("2.mp3");
									AssetFileDescriptor fileDescriptor3 = assetManager
											.openFd("3.mp3");
									AssetFileDescriptor fileDescriptor4 = assetManager
											.openFd("4.mp3");
									AssetFileDescriptor fileDescriptor5 = assetManager
											.openFd("5.mp3");
									if (b < 1.0) {
										player.setDataSource(fileDescriptor1
												.getFileDescriptor(),
												fileDescriptor1
														.getStartOffset(),
												fileDescriptor1.getLength());
									} else if (b >= 1.0 && b < 2.0) {
										player.setDataSource(fileDescriptor2
												.getFileDescriptor(),
												fileDescriptor2
														.getStartOffset(),
												fileDescriptor2.getLength());
									} else if (b >= 2.0 && b < 3.0) {
										player.setDataSource(fileDescriptor3
												.getFileDescriptor(),
												fileDescriptor3
														.getStartOffset(),
												fileDescriptor3.getLength());
									} else if (b >= 3.0 && b < 4.0) {
										player.setDataSource(fileDescriptor4
												.getFileDescriptor(),
												fileDescriptor4
														.getStartOffset(),
												fileDescriptor4.getLength());
									} else if (b >= 4.0 && b <= 5.0) {
										player.setDataSource(fileDescriptor5
												.getFileDescriptor(),
												fileDescriptor5
														.getStartOffset(),
												fileDescriptor5.getLength());
									}

									player.prepare();
									player.start();
								} catch (Exception e) {
									Log.i("test", e.toString());
								}
							}

						}
					}

					// 扩展接口，暂时没有回调
					@Override
					public void onEvent(int arg0, int arg1, int arg2,
							Bundle arg3) {

					}

					// 出错回调
					@Override
					public void onError(SpeechError error) {

						isShowDialog = false;

						if (null != popupWindow && popupWindow.isShowing()) {
							popupWindow.dismiss();
						}

						if (null != llLoading) {
							llLoading.setVisibility(View.INVISIBLE);
						}

						if (null != tvScore) {
							tvScore.setVisibility(View.INVISIBLE);
						}

						if (null != btNext) {
							btNext.setVisibility(View.INVISIBLE);
						}

						UiHelper.toast(getActivity(), "请重新录音");
					}

					// 说话结束回调
					@Override
					public void onEndOfSpeech() {
					}

					// 开始说话回调
					@Override
					public void onBeginOfSpeech() {

					}
				});
	}

	/**
	 * 设置讯飞语音录制对象的参数方法
	 */
	private void setParams() {

		mSpeechEvaluator = SpeechEvaluator.createEvaluator(getActivity(), null);

		// 设置评测语种
		mSpeechEvaluator.setParameter(SpeechConstant.LANGUAGE, "en_us");

		// 设置评测题型
		// mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY,
		// "read_word");//单词

		mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY,
				"read_sentence");// 句子

		// 设置试题编码类型
		mSpeechEvaluator.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");

		// 设置前、后端点超时
		mSpeechEvaluator.setParameter(SpeechConstant.VAD_BOS, "5000");
		mSpeechEvaluator.setParameter(SpeechConstant.VAD_EOS, "1800");

		// 设置录音超时，设置成-1 则无超时限制
		mSpeechEvaluator.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, "-1");

		// 设置结果等级，不同等级对应不同的详细程度
		mSpeechEvaluator.setParameter(SpeechConstant.RESULT_LEVEL, "complete");

		// 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
		// 注：AUDIO_FORMAT参数语记需要更新版本才能生效
		mSpeechEvaluator.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");

		// 配置录音文件存放的位置
		// mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
		// Environment.getExternalStorageDirectory().getAbsolutePath()
		// + "/msc/" + "ice" + postion + ".wav");

	}

	/**
	 * 根据当前页面获取录音文件的路径的方法
	 * 
	 * @return
	 */
	private String getAmrPath(int postion) {
		File file = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/msc/" + "ice" + postion + ".wav");
		return file.getAbsolutePath();
	}

	/**
	 * 播放选择正确答案后录音的方法
	 */
	private void playRightAnswer(int resId) {
		// 创建音频播放对象
		if (player != null) {
			player.release();
			player = null;
			player = MediaPlayer.create(getActivity(), resId);
		} else {
			player = MediaPlayer.create(getActivity(), resId);
		}

		player.start();

		// 设置完成播放的监听
		player.setOnCompletionListener(new rightAnswerListener());

	}

	@Override
	public void onDestroy() {
		if (null != player) {
			player.release();
			player = null;
		}
		super.onDestroy();

	}

	/**
	 * MediaPlayer的播放完成的监听事件(底部录音按钮)
	 * 
	 * @author Administrator
	 *
	 */
	class setEnableListener implements OnCompletionListener {

		@Override
		public void onCompletion(MediaPlayer mp) {
			if (player != null) {
				player.release();
				player = null;
			}

			// 清除动画效果
			if (null != animationDrawable) {
				animationDrawable.stop();
				lvRecord.setImageResource(R.drawable.recordcloze);
			}

		}
	}

	/**
	 * MediaPlayer的播放完成的监听事件(顶部的喇叭)
	 * 
	 * @author Administrator
	 *
	 */
	class topLabaListener implements OnCompletionListener {

		@Override
		public void onCompletion(MediaPlayer mp) {
			// 结束顶部的ImageView帧动画
			if (null != animationDrawable) {
				animationDrawable.stop();
			}

			// 恢复小喇叭的显示图标
			lvTopLaBa.setImageResource(R.drawable.lb);

			if (player != null) {
				player.release();
				player = null;
			}
		}
	}

	/**
	 * MediaPlayer的播放完成的监听事件(顶部的喇叭)
	 * 
	 * @author Administrator
	 *
	 */
	class lvReplayListener implements OnCompletionListener {

		@Override
		public void onCompletion(MediaPlayer mp) {

			// 改变图标
			lvReplay.setImageResource(R.drawable.playcloze);
			if (player != null) {
				player.release();
				player = null;
			}
		}
	}

	/**
	 * MediaPlayer的播放完成的监听事件(选择正确后播放选对的录音的监听)
	 */
	class rightAnswerListener implements OnCompletionListener {

		@Override
		public void onCompletion(MediaPlayer mp) {
			// 释放资源对象
			if (player != null) {
				player.release();
				player = null;
			}
		}
	}

	/**
	 * 广播接受者
	 */
	class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			// 释放资源对象
			if (player != null) {
				player.release();
			}

			// 停止动画资源
			if (null != animationDrawable) {
				animationDrawable.stop();
			}

			// 设置顶部喇叭的图片
			lvTopLaBa.setImageResource(R.drawable.lb);

			// 设置底部的播放按钮的图片
			lvReplay.setImageResource(R.drawable.playcloze);

			// 让PopUpWindow消失
			if (null != popupWindow && popupWindow.isShowing()) {
				popupWindow.dismiss();
			}
		}
	}

	/**
	 * 录音的触摸事件
	 * 
	 * @param v
	 * @param event
	 * @return
	 */
	@Override
	public boolean onTouch(View v, MotionEvent event) {

		switch (event.getAction()) {

		case MotionEvent.ACTION_DOWN:

			// 按下的时候重置状态
			isShowDialog = true;

			// 隐藏加载显示分数,下一步按钮
			llLoading.setVisibility(View.INVISIBLE);
			tvScore.setVisibility(View.INVISIBLE);
			btNext.setVisibility(View.INVISIBLE);

			// 按下的操作
			showRecordPop();

			// 同时开始录音并播放
			doRecordAction();

			break;

		case MotionEvent.ACTION_UP:

			// 停止评测方法
			if (null != mSpeechEvaluator) {
				mSpeechEvaluator.stopEvaluating();
			}

			// 松下的操作
			if (null != popupWindow && popupWindow.isShowing()) {
				popupWindow.dismiss();
			}

			// 松手的时候开始加载框转圈功能
			if (null != llLoading) {
				if (isShowDialog) {
					llLoading.setVisibility(View.VISIBLE);
				} else {
					llLoading.setVisibility(View.INVISIBLE);
				}
			}

		}

		return true;
	}

	/**
	 * 弹出录音的PopUpwindow
	 */
	private void showRecordPop() {

		view = View.inflate(getActivity(), R.layout.pop_record, null);

		lvPopRecord = (ImageView) view.findViewById(R.id.lv_pop_record);
		// 给顶部的图片设置帧动画
		lvPopRecord.setImageResource(R.drawable.record_anim);

		// 获取帧动画对象
		popAnimationDrawable = (AnimationDrawable) lvPopRecord.getDrawable();

		// 开启帧动画
		popAnimationDrawable.start();

		popupWindow = new PopupWindow(view,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT);

		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());

		popupWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				if (null != popAnimationDrawable) {
					popAnimationDrawable.stop();
				}
			}
		});
		popupWindow.showAtLocation(getActivity().getWindow().getDecorView(),
				Gravity.CENTER, 0, 0);
	}
}
